import 'package:flutter_widget/custom/custom_appbar.dart';
import 'package:flutter_widget/custom/custom_button.dart';
import 'package:flutter_widget/utils/platform.dart';
import 'package:flutter/material.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'dart:io';

import 'package:webview_flutter/webview_flutter.dart';

class BarcodeScan2Page extends StatefulWidget {
  const BarcodeScan2Page({Key? key, required this.name}) : super(key: key);
  final String name;

  @override
  State<BarcodeScan2Page> createState() => _BarcodeScan2PageState();
}

class _BarcodeScan2PageState extends State<BarcodeScan2Page> {
  @override
  void initState() {
    super.initState();
    // Enable virtual display.
    if (PlatformUtils.isAndroid) WebView.platform = AndroidWebView();
  }

  String url = '';
  // ignore: non_constant_identifier_BarcodeScan2Pages
  //扫描二维码
  static Future<String?> getQrcodeState() async {
    try {
      const ScanOptions options = ScanOptions(
        strings: {
          'cancel': '取消',
          'flash_on': '开启闪光灯',
          'flash_off': '关闭闪光灯',
        },
      );
      final ScanResult result = await BarcodeScanner.scan(options: options);
      return result.rawContent;
      // ignore: empty_catches
    } catch (e) {}
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CustomAppbar(widget.name, Theme.of(context).primaryColor),
        body: Center(
            child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: url.length>0
              ? WebView(
                  initialUrl: url,
                )
              : CustomButton(
                  title: '扫描二维码',
                  onPressed: () {
                    getQrcodeState().then(
                      (value) => setState(
                        () {
                          print(value);
                          if (value != null) {
                            setState(() {
                              url = value;
                            });
                          }
                        },
                      ),
                    );
                  },
                ),
        )));
  }
}
